package com.jianan.mis.app.overseastudy;

import static com.jianan.mis.util.ui.calendar.SWTCalendarWrapper.openCalendar;
import static com.jianan.mis.util.ui.table.TableCreator.createSortedTableColumn;

import java.text.Collator;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;

import com.jianan.mis.data.cache.CountryCache;
import com.jianan.mis.data.cache.EmployeeCache;
import com.jianan.mis.data.domain.Country;
import com.jianan.mis.data.domain.Employee;
import com.jianan.mis.service.OsConsultationService;
import com.jianan.mis.sys.IImageKeys;
import com.jianan.mis.sys.IMessageKeys;
import com.jianan.mis.sys.ImageManager;
import com.jianan.mis.sys.ResourceManager;
import com.jianan.mis.sys.SpringBeanFactory;
import com.jianan.mis.util.StringUtils;
import com.jianan.mis.util.ui.table.AbstractInvertableTableSorter;

public class OsConsultationStatView extends ViewPart {

	class TableLabelProvider extends LabelProvider implements ITableLabelProvider {
		public String getColumnText(Object element, int columnIndex) {
			if (comboType.getSelectionIndex() >= 0)
				return ((Object[]) element)[columnIndex].toString();
			else if (columnIndex == 0)
				return element.toString();
			else
				return "";
		}
		public Image getColumnImage(Object element, int columnIndex) {
			return null;
		}
	}
	class ContentProvider implements IStructuredContentProvider {
		public Object[] getElements(Object inputElement) {
			return ((List) inputElement).toArray();
		}
		public void dispose() {
		}
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		}
	}
	
	private TableViewer statTableViewer;
	private Table statTable;
	private Combo comboType;
	private Combo comboTime;
	private Text txtTime;
	public static final String ID = "com.jianan.mis.app.overseastudy.OsConsultationStatView"; //$NON-NLS-1$

	final private SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy年");
	final private SimpleDateFormat monthFormat = new SimpleDateFormat("yyyy年MM月");
	private SimpleDateFormat currentFormat;
	
	private OsConsultationService osConsultationService;
	
	private void initializeServices() {
		osConsultationService = (OsConsultationService) SpringBeanFactory.getBean("osConsultationService");
	}

	/**
	 * Create contents of the view part
	 * @param parent
	 */
	@Override
	public void createPartControl(Composite parent) {
		
		Composite container = new Composite(parent, SWT.NONE);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.marginTop = 20;
		gridLayout.marginWidth = 20;
		gridLayout.marginHeight = 0;
		gridLayout.marginBottom = 100;
		gridLayout.marginRight = 300;
		gridLayout.makeColumnsEqualWidth = true;
		gridLayout.numColumns = 4;
		container.setLayout(gridLayout);

		final Label label = new Label(container, SWT.NONE);
		label.setFont(ResourceManager.getFont("", 10, SWT.BOLD));
		label.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1));
		label.setText("统计选项:");

		final Label label_1 = new Label(container, SWT.NONE);
		label_1.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_1.setText("时间选项:");

		comboTime = new Combo(container, SWT.READ_ONLY);
		comboTime.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if (comboTime.getSelectionIndex() == 0) {
					currentFormat = monthFormat;
				} else if (comboTime.getSelectionIndex() == 1) {
					currentFormat = yearFormat;
				} else {
					currentFormat = null;
				}
				txtTime.setText("");
			}
		});
		comboTime.setItems(new String[] {"按月", "按年"});
		final GridData gd_comboTime = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		comboTime.setLayoutData(gd_comboTime);

		final Label label_2 = new Label(container, SWT.NONE);
		label_2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_2.setText("选择咨询时间:");

		txtTime = new Text(container, SWT.BORDER);
		txtTime.setEditable(false);
		txtTime.addMouseListener(new MouseAdapter() {
			public void mouseDown(final MouseEvent e) {
				if (comboTime.getSelectionIndex() >= 0) {
					openCalendar(e, txtTime, currentFormat);
				} else {
					currentFormat = null;
				}
			}
		});
		final GridData gd_txtTime = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtTime.widthHint = 95;
		txtTime.setLayoutData(gd_txtTime);

		final Label label_3 = new Label(container, SWT.NONE);
		label_3.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_3.setText("汇总选项:");

		comboType = new Combo(container, SWT.READ_ONLY);
		comboType.setItems(new String[] {"按咨询员", "按咨询国家"});
		final GridData gd_comboType = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		comboType.setLayoutData(gd_comboType);
		new Label(container, SWT.NONE);
		new Label(container, SWT.NONE);
		new Label(container, SWT.NONE);

		final Button btnStat = new Button(container, SWT.NONE);
		btnStat.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				Date time = null;
				if (comboTime.getSelectionIndex() >= 0) {
					if(StringUtils.isEmpty(txtTime.getText())) {
						MessageDialog.openInformation(e.display.getActiveShell(),
								IMessageKeys.FAIL, "请选择时间!");
						return;
					}
					try {
						time = currentFormat.parse(txtTime.getText());
					} catch (ParseException ex) {
						ex.printStackTrace();
					}
				}
				List result = osConsultationService.getStat(comboType
						.getSelectionIndex(), comboTime.getSelectionIndex(),
						time);
				if (comboType.getSelectionIndex() == 0) {
					statTable.getColumn(0).setText("咨询员");
					statTable.getColumn(1).setText("咨询次数");
				} else if (comboType.getSelectionIndex() == 1) {
					statTable.getColumn(0).setText("咨询国家");
					statTable.getColumn(1).setText("咨询次数");
				} else {
					statTable.getColumn(0).setText("咨询总次数");
					statTable.getColumn(1).setText("");
				}
				if (result != null) {
					statTableViewer.setInput(getResult(result));
				} else {
					statTableViewer.setInput(null);
				}	
			}
		});
		btnStat.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
		btnStat.setText("统计");
		btnStat.setImage(ImageManager.getImage(IImageKeys.SEARCH_HISTORY));

		final Button btnReset = new Button(container, SWT.NONE);
		btnReset.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				comboTime.deselectAll();
				txtTime.setText("");
				comboType.deselectAll();
			}
		});
		btnReset.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
		btnReset.setText("重置");
		btnReset.setImage(ImageManager.getImage(IImageKeys.RESET));
		new Label(container, SWT.NONE);

		final Label label_4 = new Label(container, SWT.NONE);
		label_4.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1));
		label_4.setFont(ResourceManager.getFont("", 10, SWT.BOLD));
		label_4.setText("统计结果:");

		statTableViewer = new TableViewer(container, SWT.BORDER);
		statTableViewer.setLabelProvider(new TableLabelProvider());
		statTableViewer.setContentProvider(new ContentProvider());
		statTable = statTableViewer.getTable();
		statTable.setLinesVisible(true);
		statTable.setHeaderVisible(true);
		statTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 4, 1));

		initializeServices();
		initializeTableViewer();
		
		//
		createActions();
		initializeToolBar();
		initializeMenu();
	}

	public static final String NAME = "";
	public static final String TIMES = "";
	public static String[] COLUMNS = null;
	
	private void initializeTableViewer() {
		createSortedTableColumn(statTableViewer, SWT.CENTER, NAME, "", 120,
				new NameSorter(), SWT.UP, false, null).chooseColumnForSorting();		
		createSortedTableColumn(statTableViewer, SWT.CENTER, TIMES, "", 120,
				new TimesSorter(), SWT.UP, false, null);
	}
	
	private List getResult(List result) {
		Iterator iterator = result.iterator();
		if (comboType.getSelectionIndex() == 0) {
			// 按咨询员
			List<Employee> employees = EmployeeCache.getInstance().getAllEmployees();
			while(iterator.hasNext()) {
				Object[] data = (Object[]) iterator.next();
				for(Employee employee : employees) {
					if(employee.getId().equals(data[0])) {
						data[0] = employee.getName();
						break;
					}
				}
			}
		} else if (comboType.getSelectionIndex() == 1) {
			// 按咨询国家
			List<Country> countries = CountryCache.getInstance().getAllCountries();
			while(iterator.hasNext()) {
				Object[] data = (Object[]) iterator.next();
				for(Country country : countries) {
					if(country.getId().equals(data[0])) {
						data[0] = country.getName();
						break;
					}
				}
			}
		}
		
		return result;
	}

	/**
	 * Create the actions
	 */
	private void createActions() {
		// Create the actions
	}

	/**
	 * Initialize the toolbar
	 */
	private void initializeToolBar() {
	}

	/**
	 * Initialize the menu
	 */
	private void initializeMenu() {
	}

	@Override
	public void setFocus() {
		// Set the focus
	}
	
	// Convenience class which avoids casting in subclasses
	private abstract class AbstractSorter extends AbstractInvertableTableSorter {
		public int compare(Viewer viewer, Object o1, Object o2) {
			return compare((Object[]) o1, (Object[]) o2);
		}
		public abstract int compare(Object[] o1, Object[] o2);
	}
	private class NameSorter extends AbstractSorter {
		public int compare(Object[] o1, Object[] o2) {
			return Collator.getInstance().compare(o1[0].toString(),
					o2[0].toString());
		}
	}
	private class TimesSorter extends AbstractSorter {
		public int compare(Object[] o1, Object[] o2) {
			return Collator.getInstance().compare(o1[1].toString(),
					o2[1].toString());
		}
	}

}
